package com.srwl.mytx.im;

import android.text.TextUtils;
import android.util.Log;

import com.srwl.mytx.Constant;
import com.srwl.mytx.domain.LiveRoom;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.im.interf.MessageSendListener;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.utils.IDUtils;
import com.srwl.mytx.utils.Utils;

public class LiveRoomService {

    private static final String TAG = "LiveRoomService";
    private LiveRoomListener messageListener;
    private User myUserInfo;
    private LiveRoom liveRoom;

    LiveRoomService() {
    }


    synchronized void distributeMessage(Message message) {
//判断是否与当前房间id相同
        if (!isParseLiveRoom(message)) {
            return;
        }
        Integer type = message.getSubType();
        if (type == null || messageListener == null) {
            return;
        }
        switch (type) {
            case Constant.IM_TYPE_LIVE_ROOM_CHART_BARRAGE_MESSAGE:
                messageListener.onReceivedBarrageMessage(message);
                break;
            case Constant.IM_TYPE_LIVE_ROOM_CHART_MESSAGE:
                messageListener.onReceivedChatMessage(message);
                break;
            case Constant.IM_TYPE_JOIN_LIVE_ROOM:
            case Constant.IM_TYPE_JOIN_LIVE_ROOM_TEMP:
            case Constant.IM_TYPE_JOIN_LIVE_ROOM_CHANGE_ACCOUNT:
                messageListener.onUserJoin(message);
                break;
            case Constant.IM_TYPE_QUIT_LIVE_ROOM:
                messageListener.onUserQuit(message);
                break;

            default:
                messageListener.onReceivedLiveRoomPushMessage(message);
        }
    }

    public void setMessageListener(LiveRoomListener messageListener) {
        this.messageListener = messageListener;
    }

    /**
     * 加入直播间
     */
    public void joinLiveRoom(LiveRoom liveRoom) {
        if (liveRoom == null) {
            Log.e(TAG, "joinLiveRoom: liveRoom 为空，，，，");
            return;
        }
        this.liveRoom = liveRoom;
        myUserInfo = UserProfileManager.getInstance().getLoginUserInfo();
        boolean tempUser = Utils.isTempUser(myUserInfo);
        if (tempUser) {
            sendJoinLiveRoomMessage(liveRoom, Constant.IM_TYPE_JOIN_LIVE_ROOM_TEMP);
        } else {
            sendJoinLiveRoomMessage(liveRoom, Constant.IM_TYPE_JOIN_LIVE_ROOM);
        }
    }

    private void sendJoinLiveRoomMessage(LiveRoom liveRoom, int msgSubType) {
        Message message = new Message();
        message.setId(IDUtils.genOrderItemId());
        message.setToId(liveRoom.getId());
        message.setFromId(myUserInfo.getuId());
        String username = myUserInfo.getUsername() != null ? myUserInfo.getUsername() : myUserInfo.getNick();
        message.setTitle(username);
        message.setIcon(myUserInfo.getAvatar());
        message.setType(Constant.LIVE_ROOM_MESSAGE);
        message.setSubType(msgSubType);

//        message.setExtraData(JSONObject.toJSONString(liveRoom));
        MessageProcessor.getInstance().sendRealTimeMessage(message, new MessageSendListener() {
            @Override
            public void onMessageSendComplete() {
                message.setContent("进来了");
                if (messageListener != null) {
                    messageListener.onUserJoin(message);
                }
            }

            @Override
            public void onMessageSendFail(String reason) {
                message.setContent("进入失败，请退出重试...");
                if (messageListener != null) {
                    messageListener.onReceivedChatMessage(message);
                }
            }
        });
    }


    /**
     * 切换账户后，进入直播间
     * 用于临时用户从直播间登录后
     * 这个方法进入直播间，后端不会推送直播间聊天记录
     *
     * @param liveRoom
     */
    public void changeAccountJoinLiveRoom(LiveRoom liveRoom) {
        if (liveRoom == null) {
            Log.e(TAG, "joinLiveRoom: liveRoom 为空，，，，");
            return;
        }
        this.liveRoom = liveRoom;
        myUserInfo = UserProfileManager.getInstance().getLoginUserInfo();
        sendJoinLiveRoomMessage(liveRoom, Constant.IM_TYPE_JOIN_LIVE_ROOM_CHANGE_ACCOUNT);

    }

    /**
     * 退出直播间
     */
    public void quitLiveRoom() {
        if (liveRoom == null) {
            Log.e(TAG, "quitLiveRoom: 必须先设置直播间");
            return;
        }
        Message message = new Message();
        message.setId(IDUtils.genOrderItemId());
        message.setToId(liveRoom.getId());
        message.setFromId(myUserInfo.getuId());
        String username = myUserInfo.getUsername() != null ? myUserInfo.getUsername() : myUserInfo.getNick();
        message.setTitle(username);
        message.setType(Constant.LIVE_ROOM_MESSAGE);
        message.setSubType(Constant.IM_TYPE_QUIT_LIVE_ROOM);
        // message.setExtraData(JSONObject.toJSONString(liveRoom));
        MessageProcessor.getInstance().sendRealTimeMessage(message, new MessageSendListener() {
            @Override
            public void onMessageSendComplete() {
                Log.i(TAG, "onMessageSendFail: 发送退出焦点信息完成");
                distributeMessage(message); //把自己发出的消息 回显给自己
            }

            @Override
            public void onMessageSendFail(String reason) {
                Log.e(TAG, "onMessageSendFail: 发送退出焦点信息失败：" + reason);
            }
        });
        liveRoom = null;
        // messageListener = null;
    }


    public void sendMessage(Message message) {


        MessageProcessor.getInstance().sendRealTimeMessage(message, new MessageSendListener() {
            @Override
            public void onMessageSendComplete() {
                distributeMessage(message); //把自己发出的消息 回显给自己
            }

            @Override
            public void onMessageSendFail(String reason) {
                message.setContent("消息发送失败... 请检查网络");
                messageListener.onReceivedChatMessage(message);
            }
        });
    }

    /**
     * 退出直播间 清理
     */
    public void clear() {
        messageListener = null;
    }


    /**
     * 判断发送的消息是否为当前房间
     *
     * @return
     */
    private boolean isParseLiveRoom(Message message) {
        String liveRoomId = message.getToId();
        if (liveRoom != null && !TextUtils.equals(liveRoomId, liveRoom.getId())) {
            Log.e(TAG, "isParseLiveRoom: 直播间没匹配上，收到的消息非本直播间的，这个情况一般是 用户没有正常退出直播间导致" + message.toString() + "当前直播间ID:" + liveRoom.getId());
            return false;
        }
        return true;
    }
}
